#include "mythread.h"
#include <QDebug>

MyThread::MyThread(qintptr id, QObject *parent)
    : QThread(parent)
{
    this->socketDescriptor = id;
}

MyThread::~MyThread()
{

}

void MyThread::run()
{
    qDebug() << "Thread start.";
    socket = new QTcpSocket;

    //set socket id
    if (!socket->setSocketDescriptor(socketDescriptor)){
        emit error(socket->error());
        return ;
    }

    // connect socket and signal
    // note ­ Qt::DirectConnection is used because it's multithreaded
    //        This makes the slot to be invoked immediately
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnect()));

    qDebug() << socketDescriptor << " Client connected.";

    // make this thread a loop,
    // thread will stay alive so that signal/slot to function properly
    // not dropped out in the middle when thread dies
    exec();
}

void MyThread::readyRead()
{
    QByteArray data = socket->readAll();

    qDebug() << socketDescriptor << " Data in: " << data;

    socket->write(data.toUpper());
}

void MyThread::disconnect()
{
    qDebug() << socketDescriptor << " Disconnected.";
    socket->deleteLater();

    exit (0);
}

